<template>
	<jk-view :loading="contentLoading">
		<el-card class="schedule-container" :body-style="{ paddingTop: '10px' }">
			<el-row class="date-nav">
				<el-col :span="8">
					<el-dropdown class="option-space" @command="onSelectWorkshop">
						<el-button :size="buttonSize" icon="">{{ searchParams.workshopName ? searchParams.workshopName : '暂无区域' }}<i class="el-icon-arrow-down el-icon--right"></i></el-button>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item
								v-for="item in workshopList"
								:key="item.id"
								:command="item.id"
								icon="el-icon-s-home"
							>{{ item.name }}</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</el-col>
				<el-col :span="8" class="flex-center month-title">
					<div class="el-icon-date" @click="onRefreshButton">{{ currentMonth }}</div>
				</el-col>
				<el-col :span="8" class="flex-end-center">
					<el-button-group>
						<el-button :size="buttonSize" icon="el-icon-d-arrow-left" @click="onPreMonthButton"></el-button>
						<el-button :size="buttonSize" icon="" @click="onCurrentMonthButton">本月</el-button>
						<el-button :size="buttonSize" icon="el-icon-d-arrow-right" @click="onNextMonthButton"></el-button>
					</el-button-group>
				</el-col>
			</el-row>
			<div class="week-header-container">
				<span v-for="(item, index) in dateHeader" :key="index" class="week-header">{{ item }}</span>
			</div>
			<el-checkbox-group v-model="checkList" class="date-container" @change="onCheckBoxChange">
				<div v-for="(allItem, allIndex) in dateList" :key="allIndex" class="date-body">
					<!--日期-->
					<div v-for="(item) in allItem" :key="item.date" class="date-body-item" :style="isCurrentDate(item)" @click="onClickDate(item)">
						<div v-if="item.isCurrentMonth" class="date-item-num" :style="{opacity: !item.isCurrentMonth ? '0.4' : ''}">{{ item.day }}</div>
						<div v-if="item.itemList && item.itemList.length" style="width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;color: #2d8cf0;cursor: pointer;" @click="onSeeMachineBtn(item)">任务数：{{ item.itemList.length }}</div>
					</div>
				</div>
			</el-checkbox-group>
		</el-card>
		<see-task-dialog
			:date-item="dateItem"
			:dialog-state="seeTaskDialogState"
			@on-visible-change="onVisibleChangeSeeTaskDialog"
			@on-confirm="onConfirmButtonSeeTaskDialog"
		/>
	</jk-view>
</template>
<script>
    import { formatDate } from '../../../../utils/jk/jk-tool';
    import seeTaskDialog from './see-task-dialog';
    import handlerCache from '../../../../mixins/handler-cache';
    import { machineManagerUpkeepMachineJobGetSchedule } from '../../../../api/machine/upkeepTask';

    export default {
        components: { seeTaskDialog },
        mixins: [handlerCache],
        data() {
            return {
                dateItem: {},
                buttonSize: 'mini',
                dateData: [],
                seeTaskDialogState: false,
                checkList: [],
                workshopList: [],
                workshopName: '',
                contentLoading: false,
                dateHeader: ['日', '一', '二', '三', '四', '五', '六'],
                dateList: [],
                rawData: [],
                currentMonth: '',
                currentDate: '',
                checkDates: [],
                clickDate: {},
                toMounted: false,
                searchParams: {
                    workshopId: null
                }
            };
        },
        computed: {
            isCurrentDate() {
                return (item) => {
                    if (item.isCurrentMonth && formatDate(Date.parse(item.date)) === formatDate(Date.parse(this.currentDate))) {
                        return {
                            background: '#f8f8f9'
                        };
                    }
                };
            }
        },
        methods: {
            onSeeMachineBtn(e) {
                this.dateItem = {
                    date: e.date,
                    workshopId: this.searchParams.workshopId
                };
                this.seeTaskDialogState = true;
            },
            clearCacheMethod() {
                this.checkDates = [];
                this.checkList = [];
                this.getInitData();
            },
            getInitData() {
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.$set(this.searchParams, 'workshopName', this.$store.state.user.userWorkshop.defaultWorkshopName);
                this.contentLoading = true;
                this.currentMonth = this.getCurrentMonth();
                this.getMonthDays(this.currentMonth);
            },
            onSelectWorkshop(e) {
                if (e) {
                    this.$set(this.searchParams, 'workshopId', e);
                    this.$set(this.searchParams, 'workshopName', this.workshopList.find(x => x.id === e) ? this.workshopList.find(x => x.id === e).name : '');
                }
                this.getMonthDays(this.currentMonth);
            },
            onRefreshButton() {
                this.getUpkeepTaskListRequest();
                this.getDataRequest();
            },
            getUpkeepTaskListRequest() {
                this.checkList = [];
                this.checkDates = [];
                this.contentLoading = true;
                // 分组（7天为一组）
                const arr = [];
                for (let i = 0, len = this.rawData.length; i < len; i += 7) {
                    arr.push(this.rawData.slice(i, i + 7));
                }
                this.dateList = JSON.parse(JSON.stringify(arr));
                const d = new Date(this.currentMonth);
                const year = d.getFullYear();
                const month = d.getMonth() + 1;
                return machineManagerUpkeepMachineJobGetSchedule({
                    workshopId: this.searchParams.workshopId,
                    year: year,
                    month: month
                }).then(res => {
                    this.contentLoading = false;
                    if (res.data.status === 200) {
                        this.rawData.forEach(item => {
                            res.data.res.forEach(resItem => {
                                if (resItem.belongDate === item.date) {
                                    item.itemList = JSON.parse(JSON.stringify(resItem.itemList));
                                }
                            });
                        });
                        // 分组（7天为一组）
                        const arr = [];
                        for (let i = 0, len = this.rawData.length; i < len; i += 7) {
                            arr.push(this.rawData.slice(i, i + 7));
                        }
                        this.dateList = JSON.parse(JSON.stringify(arr));
                    }
                });
            },
            onConfirmButtonSeeTaskDialog() {
                this.seeTaskDialogState = false;
                this.getMonthDays(this.currentMonth);
            },
            onVisibleChangeSeeTaskDialog(e) {
                this.seeTaskDialogState = e;
                if (!e) {
                    this.getUpkeepTaskListRequest(this.currentMonth);
                }
            },
            onCheckBoxChange(e) {
                this.checkDates = e;
            },
            onClickDate(e) {
                this.clickDate = e;
            },
            // 获取当前月份
            getCurrentMonth() {
                const d = new Date(Date.now());
                const month = d.getMonth() + 1;
                const day = d.getDate();
                this.currentDate = `${d.getFullYear()}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
                return `${d.getFullYear()}-${month < 10 ? '0' + month : month}`;
            },
            onPreMonthButton() {
                this.currentMonth = this.getPreMonth(this.currentMonth);
                this.getMonthDays(this.currentMonth);
            },
            onCurrentMonthButton() {
                this.currentMonth = this.getCurrentMonth();
                this.getMonthDays(this.currentMonth);
            },
            onNextMonthButton() {
                this.currentMonth = this.getNextMonth(this.currentMonth);
                this.getMonthDays(this.currentMonth);
            },
            // 上一个月
            getPreMonth(date) {
                const d = new Date(date);
                let year = d.getFullYear();
                let month = d.getMonth();
                if (month === 0) {
                    year = year - 1;
                    month = 12;
                }
                return `${year}-${month < 10 ? '0' + month : month}`;
            },
            // 下一个月
            getNextMonth(date) {
                const d = new Date(date);
                let year = d.getFullYear();
                let month = d.getMonth() + 1;
                month = month + 1;
                if (month === 13) {
                    year = year + 1;
                    month = 1;
                }
                return `${year}-${month < 10 ? '0' + month : month}`;
            },
            // 获取某个月的天数
            getMonthDays(date) {
                const d = new Date(date);
                const year = d.getFullYear();
                const month = d.getMonth() + 1;
                const days = new Date(year, month, 0).getDate();
                this.rawData = [];
                // 所选月份的所有天数
                for (let i = 1; i <= days; i++) {
                    this.rawData.push({
                        date: `${date}-${i < 10 ? '0' + i : i}`,
                        timeStamp: Date.parse(`${date}-${i < 10 ? '0' + i : i}`),
                        day: i,
                        isCurrentMonth: true
                    });
                }
                // 获取所选月份的1号是星期几
                const firstDayToWeek = new Date(`${date}-1`).getDay();
                // 获取所选月份的最后一天是星期几
                const lastDayToWeek = 7 - (new Date(`${date}-${days}`).getDay() + 1);

                // 在前面填充上月的日期
                for (let i = 1; i <= firstDayToWeek; i++) {
                    this.rawData.unshift({
                        date: formatDate(Date.parse(`${date}-1`) - (i * 24 * 60 * 60 * 1000)),
                        timeStamp: Date.parse(`${date}-1`) - (i * 24 * 60 * 60 * 1000),
                        day: new Date(Date.parse(`${date}-1`) - (i * 24 * 60 * 60 * 1000)).getDate(),
                        isCurrentMonth: false
                    });
                }
                // 在后面填充下月的日期
                for (let i = 1; i <= lastDayToWeek; i++) {
                    this.rawData.push({
                        date: formatDate(Date.parse(`${date}-${days}`) + (i * 24 * 60 * 60 * 1000)),
                        timeStamp: Date.parse(`${date}-${days}`) + (i * 24 * 60 * 60 * 1000),
                        day: new Date(Date.parse(`${date}-${days}`) + (i * 24 * 60 * 60 * 1000)).getDate(),
                        isCurrentMonth: false
                    });
                }
                this.dateData = JSON.parse(JSON.stringify(this.rawData));
                this.getUpkeepTaskListRequest();
            }
        },
        mounted() {
            this.toMounted = true;
            this.getInitData();
        }
    };
</script>
<style scoped lang="scss">
    //@import "./schedule.scss";
    /*
    加check-group后样式冲突的问题
*/
    $border_color: #dfe6ec;
    $date_num_color: #808695;
    $shift_color: #ff9900;
    $group_color: #2b85e4;
    .el-checkbox-group {
        font-size: 1px;
    }

    .schedule-container {
        margin-top: 20px;
        .date-nav {
            width: 100%;
            font-weight: bold;
            border-radius: 8px 8px 0 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin: 8px 0;
            .month-title {
                font-size: 32px;
                letter-spacing: 3px;
                font-weight: 700;
                color: #2b85e4;
            }
            .month-title div:hover {
                color: #2d8cf0;
                cursor: pointer;
            }
        }

        .week-header-container {
            width: 100%;
            border-radius: 6px 6px 0 0;
            overflow: hidden;
            border: 1px solid #dcdee2;
            border-bottom: none;
            .week-header {
                width: calc(100% / 7);
                height: 40px;
                display: inline-block;
                background: #f8f8f9;
                line-height: 40px;
                text-align: center;
                box-sizing: border-box;
            }
        }
        .week-header-container .week-header:last-child {
            border-right: none;
        }

        .date-container {
            max-height: calc(100vh - 230px);
            overflow: auto;
            border: solid 1px #dcdee2;
            border-top: solid 1px #dcdee2;
            border-bottom: none;
            box-sizing: border-box;
            scrollbar-width: none!important;
            border-radius: 0 0 6px 6px;
            .date-body {
                width: 100%;
                display: flex;
                background: #fff;
                .date-body-item {
                    width: calc(100% / 7);
                    height: 100%;
                    min-height: 100px;
                    display: table;
                    font-size: 14px;
                    padding: 4px 2px 4px 2px;
                    color: #ccc;
                    text-align: center;
                    border-bottom: 1px solid $border_color;
                    border-right: 1px solid $border_color;
                    position: relative;
                    box-sizing: border-box;
                    .check-box-position {
                        position: absolute;
                        left: 6px;
                        top: 4px;
                    }
                    .date-item-num {
                        line-height: 32px;
                        position: absolute;
                        top: 0;
                        right: 4px;
                        font-size: 24px;
                        font-family: Serif;
                        color: $date_num_color;
                        z-index: 1;
                        font-weight: 100;
                    }
                    .date-option-box {
                        width: 100%;
                        font-size: 12px;
                        line-height: 16px;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: flex-start;
                        z-index: 2;
                        .option-type-circle-icon {
                            width: 4px;
                            height: 4px;
                            border-radius: 50%;
                            background: $shift_color;
                        }
                        .date-option-item {
                            width: 100%;
                            display: flex;
                            margin-top: 4px;
                            align-items: center;
                            flex-wrap: wrap;
                            border-radius: 4px;
                            padding: 2px 2px 2px 4px;
                            .option-type-name {
                                margin-left: 2px;
                                text-align: left;
                                white-space: nowrap;
                                color: $shift_color;
                            }

                            .date-option-item-item {
                                margin-right: 6px;

                            }
                            .option-msg-item {
                                color: #515a6e;
                                white-space: nowrap;
                                margin-left: 4px;
                            }
                            .option-msg-item:hover {
                                color: $group_color;
                                cursor: pointer;
                            }
                        }
                    }
                    .date-item-null {
                        width: 90%;
                        height: 24px;
                        font-size: 16px;
                        font-weight: 100;
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;
                        color: #c5c8ce;
                        position: absolute;
                        top: 50%;
                        margin-top: -12px;
                    }
                }
                .date-body-item:hover {
                    background: #e8f4ff;
                    transition: .2s;
                    .date-item-num {
                    }
                    .date-option-item {
                        background: #fff;
                    }
                }
            }
            .date-body .date-body-item:last-child {
                border-right: none;
            }
        }
        .date-container::-webkit-scrollbar{
            overflow: hidden;
            scrollbar-width: none!important;
            width: 0!important;
            height: 0;
        }
    }

</style>
